﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Web.Mvc;
using System.Web.Security;
using DotNet.Mvc;

namespace DotNet.Edu.WebUtility
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public sealed class DomainLogInAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var requestedWith = filterContext.HttpContext.Request.Headers["X-Requested-With"];
            var key = "_dotnet_edu_user_";
            if (filterContext.HttpContext.Session != null
                && filterContext.HttpContext.Session[key] == null)
            {
                if (!string.IsNullOrEmpty(requestedWith) && requestedWith.Equals("XMLHttpRequest"))
                {
                    filterContext.Result = new JsonNetResult(new { type="session_timeout", success = false, message = "登录超时", url = FormsAuthentication.LoginUrl });
                    filterContext.HttpContext.Response.Clear();
                    filterContext.HttpContext.Response.StatusCode = 500;
                    filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    filterContext.HttpContext.Response.ContentType = "application/json";
                }
                else
                {
                    filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl);
                }
            }
        }
    }
}